package com.dingding.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingding.gmall.common.constant.ProductConstant;
import com.dingding.gmall.common.utils.PageUtils;
import com.dingding.gmall.common.utils.Query;
import com.dingding.gmall.product.dao.AttrAttrgroupRelationDao;
import com.dingding.gmall.product.dao.AttrDao;
import com.dingding.gmall.product.dao.AttrGroupDao;
import com.dingding.gmall.product.dao.CategoryDao;
import com.dingding.gmall.product.entity.AttrAttrgroupRelationEntity;
import com.dingding.gmall.product.entity.AttrEntity;
import com.dingding.gmall.product.entity.AttrGroupEntity;
import com.dingding.gmall.product.entity.CategoryEntity;
import com.dingding.gmall.product.service.AttrAttrgroupRelationService;
import com.dingding.gmall.product.service.AttrService;
import com.dingding.gmall.product.service.CategoryService;
import com.dingding.gmall.product.vo.AttrGroupRelationVO;
import com.dingding.gmall.product.vo.AttrResponseVO;
import com.dingding.gmall.product.vo.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), new QueryWrapper<>());
        return new PageUtils(page);
    }


    @Override
    @Transactional
    public void saveAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //保存基本数据
        this.save(attrEntity);
        //保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrEntity.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        //1-规格参数
        //0-销售属性
        int result = "base".equalsIgnoreCase(attrType)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type",result);
        //catelogId==0查所有
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id",catelogId);
        }
        //模糊条件
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)){
            queryWrapper.and(wrapper -> wrapper.eq("attr_id",key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        if (CollectionUtils.isNotEmpty(records)){
            List<AttrResponseVO> attrResponseVOList = records.stream().map(attrEntity -> {
                AttrResponseVO attrResponseVO = new AttrResponseVO();
                BeanUtils.copyProperties(attrEntity, attrResponseVO);
                /** 销售属性是没有所属分组的 **/
                if (result == 1) {
                    //1、设置分组
                    AttrAttrgroupRelationEntity attrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                    if (attrgroupRelationEntity != null && attrgroupRelationEntity.getAttrGroupId() != null) {
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
                        attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
                //2、设置分类
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                if (categoryEntity != null) {
                    attrResponseVO.setCatelogName(categoryEntity.getName());
                }
                return attrResponseVO;
            }).collect(Collectors.toList());
            pageUtils.setList(attrResponseVOList);
        }
        return pageUtils;
    }


    @Override
    public AttrResponseVO getAttrInfo(Long attrId) {
        AttrResponseVO attrResponseVO = new AttrResponseVO();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrResponseVO);
        //1、获取分组信息
        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            if (relationEntity != null) {
                attrResponseVO.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //2、获取分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrResponseVO.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrResponseVO.setCatelogName(categoryEntity.getName());
        }
        return attrResponseVO;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //1、修改基本数据
        this.updateById(attrEntity);
        //2、修改关联分组
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
//            relationService.saveOrUpdate(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntityList = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        if (CollectionUtils.isNotEmpty(relationEntityList)){
            List<Long> attrIds = relationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
            return (List<AttrEntity>) attrEntities;
        }
        return new ArrayList<>();
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVO> list) {
        relationDao.deleteBatchRelation(list);
    }

    @Override
    public PageUtils getNoRelation(Map<String, Object> params, Long attrgroupId) {
        //1、查找当前分组只能关联自己所属分类的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2 查找当前分组只能关联别的分组没有引用的属性
        //2.1 找到当前分类下的其他分组
        List<AttrGroupEntity> attrGroupEntityList = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", catelogId)
//                        .ne("attr_group_id",attrgroupId)
        );
        //2.2 找到这些分组关联的属性
        if (CollectionUtils.isNotEmpty(attrGroupEntityList)) {
            List<Long> attrGroupIds = attrGroupEntityList.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
            List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = relationDao.selectList(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds)
            );
            //3.3 从当前分类的所有属性中移除这些属性
            if (CollectionUtils.isNotEmpty(attrgroupRelationEntityList)) {
                List<Long> attrids = attrgroupRelationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
                QueryWrapper<AttrEntity> warpper = new QueryWrapper<AttrEntity>()
                        .eq("catelog_id", catelogId)
                        .notIn("attr_id", attrids)
                        .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
                String key = (String) params.get("key");
                if (StringUtils.isNotBlank(key)){
                    warpper.and(item -> {
                        item.eq("attr_id",key).or().like("attr_name",key);
                    });
                }
                IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), warpper);
                return new PageUtils(page);
            }
        }
        return new PageUtils();
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> collect) {
        return baseMapper.selectSearchAttrIds(collect);
    }
}